package com.zzzzzz.content.picitem;

import java.net.URLEncoder;
import java.util.List;
import java.util.Locale;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.zzzzzz.account.signin.NoSuchOnlineUserException;
import com.zzzzzz.account.signin.OnlineService;
import com.zzzzzz.common.message.Message;
import com.zzzzzz.common.message.MessageIcon;
import com.zzzzzz.common.page.PageStart;
import com.zzzzzz.content.Constants;
import com.zzzzzz.content.reply.ReplyService;
import com.zzzzzz.content.reply.ReplyView;
import com.zzzzzz.content.tag.NoSuchTagException;

@Controller
public class PicItemController {
	@Resource
	private PicItemService picItemService;
	@Resource
	private ReplyService replyService;
	@Resource
	private OnlineService onlineService;
	
	@RequestMapping(value = "/picitem/upload/{picTextId}", method = RequestMethod.GET)
	public String uploadPage(@PathVariable Long picTextId, Model model) {
		model.addAttribute("picTextId", picTextId);
		return "content/picitem/upload";
	}
	
	@RequestMapping(value = "/picitem/upload", method = RequestMethod.POST)
	public @ResponseBody String upload(MultipartHttpServletRequest request, HttpServletResponse response) throws NoSuchOnlineUserException, NoSuchTagException {
		Long userId = onlineService.findUserId();
		String picTextIdStr = request.getParameter("picTextId");
		try {
			MultipartFile files = request.getFile("files");
			Long picTextId = Long.valueOf(picTextIdStr);

			PicForm picForm = new PicForm();
			picForm.setPicTextId(picTextId);
			picForm.setFiles((CommonsMultipartFile)files);
			Long picItemId = picItemService.add(userId, picForm);
			return picItemId+"";
		} catch (Exception e) {
			logger.warn("picitemAdd", e);
			return "0";
		}
	}
	
	@RequestMapping(value = "/picitem/{picItemId}/add", method = RequestMethod.GET)
	public String add(@PathVariable Long picItemId, Model model) throws Exception {
		List<PicItemListView> picItemViewList = picItemService.findByGtId(picItemId);
		model.addAttribute("picItemViewList", picItemViewList);
		model.addAttribute("picItemForm", new PicItemForm());
		return "content/picitem/add";
	}
	
	@RequestMapping(value = "/picitem/add", method = RequestMethod.POST)
	public String add(Model model, PicItemForm picItemForm, BindingResult bindingResult, RedirectAttributes redirectAttributes, Locale locale) throws NoSuchOnlineUserException, NoSuchTagException {
		Long userId = onlineService.findUserId();
		try {
			Long picTextId = picItemService.edit(userId, picItemForm);
			return "redirect:/pictext/" + picTextId;
		} catch (Exception e) {
			logger.warn("picitemAdd", e);
			redirectAttributes.addFlashAttribute(Message.error(MessageIcon.WARNING + "添加失败"));
			return "redirect:/picitem/add";
		}
	}
	
	@RequestMapping(value="/picitem/{id}", method=RequestMethod.GET)
	public String view(@PathVariable Long id, @RequestParam(value = "start", defaultValue = "0", required = false) Integer start, HttpServletRequest request, Model model) throws Exception {
		PicItemView picItemView = picItemService.findViewById(id);
		if(picItemView != null){
			picItemService.plusLooks(id);
		}
		model.addAttribute("picItemView", picItemView);
		
		picItemService.setPicItemProperty(picItemView);
		
		String replyListUrlEnd = "#replySpan";
		List<ReplyView> replyViewList = replyService.findByTopicId(id, Constants.CONTENT_DB_TYPE.PICITEM, start, PageStart.DEFAULT_OFFSET);
		Long replyViewListCount = replyService.findByTopicIdCount(id, Constants.CONTENT_DB_TYPE.PICITEM);
		PageStart replyViewListPageBar = new PageStart(start, PageStart.DEFAULT_OFFSET, replyViewListCount, "/picitem/"+id, replyListUrlEnd);
		
		model.addAttribute("replyViewList", replyViewList);
		model.addAttribute("replyViewListCount", replyViewListCount);
		model.addAttribute("replyViewListPageBar", replyViewListPageBar.getPageBar());
		
		model.addAttribute("backUrl", URLEncoder.encode("/picitem/"+id+replyListUrlEnd, "UTF-8"));
		
		return "content/picitem/view";
	}
	
	@RequestMapping(value = "/picitem/edit/{picTextId}", method = RequestMethod.GET)
	public String topicList(@PathVariable Long picTextId, 
			@RequestParam(value = "start", defaultValue = "0", required = false) Integer start, 
			HttpServletRequest request, Model model) throws NoSuchTagException {
		
		List<PicItemListView> picItemViewList = picItemService.findByPicTextId(picTextId, start, PageStart.DEFAULT_OFFSET);
		Long count = picItemService.findByPicTextIdCount(picTextId);
		PageStart pageStart = new PageStart(start, PageStart.DEFAULT_OFFSET, count, "/");
		
		model.addAttribute("picItemViewList", picItemViewList);
		model.addAttribute("count", count);
		model.addAttribute("pageBar", pageStart.getPageBar());
		
		return "content/picitem/edit";
	}
	
	@RequestMapping(value = "/picitem/seq", method = RequestMethod.POST)
	public @ResponseBody Integer editSeq(Model model, @RequestParam(value = "ids", required = true) String ids) throws NoSuchOnlineUserException {
		Long userId = onlineService.findUserId();
		try {
			picItemService.editSeqNb(ids, userId);
			return 1;
		} catch (Exception e) {
			logger.warn("editSeq", e);
			return 0;
		}
	}
	
	private static final Logger logger = LoggerFactory.getLogger(PicItemController.class);
}
